/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Presentacion;

import ModeloLogicoSistema.AdministradorStock;
import ModeloLogicoSistema.ProductoIngresado;
import ModeloLogicoSistema.Validacion;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author debo
 */
public class IngresoStock extends javax.swing.JDialog {

    private AdministradorStock stock = null;
    private ProductoIngresado productoIngresado = null;
    private ArrayList<ProductoIngresado> ListaProductosIngresados = null;
    private SimpleDateFormat formateador = new SimpleDateFormat("dd/MM/yyyy");
    private int colNombre = 0;
    private int colPrecioU = 1;
    private int colCant = 2;
    private int colSubT = 3;
    

    /**
     * Creates new form IngresoStock
     */
    public IngresoStock(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        try {
            stock = new AdministradorStock();
            for (String nombre : stock.getListaStock()) {
                this.jComboBox1.addItem(nombre);
            }
        } catch (SQLException ex) {
            Logger.getLogger(IngresoStock.class.getName()).log(Level.SEVERE, null, ex);
        }
        this.setLocationRelativeTo(null);
        this.setVisible(true);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel4 = new javax.swing.JLabel();
        btnAgregar = new javax.swing.JButton();
        labelCantidad = new javax.swing.JLabel();
        spinnerCantidad = new javax.swing.JSpinner();
        jScrollPane1 = new javax.swing.JScrollPane();
        tablaProductoIngresado = new javax.swing.JTable();
        jTPrecio = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jComboBox1 = new javax.swing.JComboBox();
        jScrollPane2 = new javax.swing.JScrollPane();
        tablaTotal = new javax.swing.JTable();
        btnConservar = new javax.swing.JButton();
        btnRechazar = new javax.swing.JButton();
        jDateChooser1 = new com.toedter.calendar.JDateChooser();
        btnQuitar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Ingresos a Stock");

        jLabel4.setText("Producto");

        btnAgregar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/agregarServicio.png"))); // NOI18N
        btnAgregar.setText("Agregar");
        btnAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAgregarActionPerformed(evt);
            }
        });
        btnAgregar.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                btnAgregarFocusGained(evt);
            }
        });

        labelCantidad.setText("Cantidad");

        spinnerCantidad.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(1), Integer.valueOf(1), null, Integer.valueOf(1)));
        spinnerCantidad.setName(""); // NOI18N
        spinnerCantidad.setValue(1);

        tablaProductoIngresado.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Producto", "Precio unitario", "Cantidad", "Subtotal"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.Double.class, java.lang.Integer.class, java.lang.Double.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tablaProductoIngresado.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(tablaProductoIngresado);

        jLabel6.setText("Precio");

        jLabel7.setText("Fecha");

        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
            }
        });

        tablaTotal.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null}
            },
            new String [] {
                "Total"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Double.class
            };
            boolean[] canEdit = new boolean [] {
                false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tablaTotal.getTableHeader().setReorderingAllowed(false);
        jScrollPane2.setViewportView(tablaTotal);

        btnConservar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/Guardar.png"))); // NOI18N
        btnConservar.setText("Guardar");
        btnConservar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnConservarActionPerformed(evt);
            }
        });

        btnRechazar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/1386214496_Delete.png"))); // NOI18N
        btnRechazar.setText("Cancelar");
        btnRechazar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRechazarActionPerformed(evt);
            }
        });

        jDateChooser1.setDateFormatString("dd/MM/yyyy");
        jDateChooser1.setMaxSelectableDate(Calendar.getInstance().getTime());

        btnQuitar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/quitar.png"))); // NOI18N
        btnQuitar.setText("Quitar");
        btnQuitar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnQuitarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(46, 46, 46)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 530, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(0, 0, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(btnConservar, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(btnRechazar, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, 56, Short.MAX_VALUE)
                            .addComponent(jLabel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jDateChooser1, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(28, 28, 28)
                                .addComponent(labelCantidad)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(spinnerCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jLabel6)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jTPrecio, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(btnAgregar, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnQuitar, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(25, 25, 25)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel7)
                    .addComponent(jDateChooser1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(40, 40, 40)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(spinnerCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(btnAgregar)
                        .addComponent(jTPrecio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel6)
                        .addComponent(labelCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(btnQuitar)))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnConservar)
                    .addComponent(btnRechazar))
                .addContainerGap(17, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregarActionPerformed
        DefaultTableModel modelo = (DefaultTableModel) tablaProductoIngresado.getModel();

        String nombre = (String) jComboBox1.getSelectedItem();
        if (nombre == null || nombre.isEmpty()) {
            return;
        }
        Integer cant, cantTotal;
        Double precio, subT;

        cant = (Integer) this.spinnerCantidad.getValue();
        if (Validacion.preciosValidos(this.jTPrecio.getText())) {
            precio = new Double(this.jTPrecio.getText());
            subT = new Double(cant * precio);
        } else {
            JOptionPane.showMessageDialog(null, "No se ha ingresado un precio válido.\nIntente nuevamente", "Precio Inválido", JOptionPane.PLAIN_MESSAGE);
            return;
        }
        boolean servicioPedidoAnteriormente = false;
        int cantFilas = modelo.getRowCount();
        int i = 0;
        while (i < cantFilas & !servicioPedidoAnteriormente) {
            String nombreCargado = modelo.getValueAt(i, colNombre).toString();
            if (nombreCargado.equalsIgnoreCase(nombre)) {
                cantTotal = (Integer) modelo.getValueAt(i, colCant) + cant;
                Double precio2 = new Double(modelo.getValueAt(i, colPrecioU).toString());
                if (precio == 0) {
                    modelo.setValueAt(cantTotal, i, colCant);
                    subT = new Double(cantTotal * precio2);
                    modelo.setValueAt(subT, i, colSubT);
                } else if (precio != precio2) {
                    Object[] opciones = {precio2, precio};
                    int opcion = JOptionPane.showOptionDialog(null, "Este producto ya fue Ingresado antes con el precio: " + precio2
                            + "\nElija el precio con el que se ingresará la cantidad total del producto.",
                            "Aviso", JOptionPane.YES_NO_OPTION, JOptionPane.DEFAULT_OPTION, null, opciones,
                            opciones[0]);
                    if (opcion == 0) {
                        modelo.setValueAt(cantTotal, i, colCant);
                        subT = new Double(cantTotal * precio2);
                        modelo.setValueAt(subT, i, colSubT);
                    }
                    if (opcion == 1) {
                        modelo.setValueAt(cantTotal, i, colCant);
                        modelo.setValueAt(precio, i, colPrecioU);
                        subT = new Double(cantTotal * precio);
                        modelo.setValueAt(subT, i, colSubT);
                    }
                    if (opcion != 0 & opcion != 1) {
                        JOptionPane.showMessageDialog(null, "No se ha podido guardar el ingreso, lo sentimos.");
                    }
                }
                servicioPedidoAnteriormente = true;
            }
            i++;
        }
        if (!servicioPedidoAnteriormente & precio != 0) {
            Object[] fila = {nombre, precio, cant, subT};
            modelo.addRow(fila);
        } else if (precio == 0 & !servicioPedidoAnteriormente) {
            JOptionPane.showMessageDialog(null, "El elemento no esta en la lista y no ha especificado precio, no se puede agregar", "Elemento no ingresado", JOptionPane.INFORMATION_MESSAGE);
        }
        cantFilas = modelo.getRowCount();
        Double total = new Double(0);
        for (int j = 0; j < cantFilas; j++) {
            Double subt = new Double(modelo.getValueAt(j, colSubT).toString());
            total = total + subt;
        }
        this.tablaTotal.setValueAt(total, 0, 0);
        this.jTPrecio.setText("");
    }//GEN-LAST:event_btnAgregarActionPerformed

    private void btnAgregarFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_btnAgregarFocusGained
        // TODO add your handling code here:
    }//GEN-LAST:event_btnAgregarFocusGained

    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jComboBox1ActionPerformed

    private void btnQuitarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnQuitarActionPerformed
        DefaultTableModel modelo = (DefaultTableModel) tablaProductoIngresado.getModel();
        try {
            int fila = this.tablaProductoIngresado.getSelectedRow();
            Double monto = (Double) modelo.getValueAt(fila, colSubT);
            modelo.removeRow(fila);
            Double montoTotal = (Double) this.tablaTotal.getValueAt(0, 0);
            Double nuevoTotal = montoTotal - monto;
            this.tablaTotal.setValueAt(nuevoTotal, 0, 0);

        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "No se ha podido remover el producto seleccionado", "Error", JOptionPane.INFORMATION_MESSAGE);
        }


    }//GEN-LAST:event_btnQuitarActionPerformed

    private void btnConservarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConservarActionPerformed
        Date FechaIngreso;
        String fecha;
        try {
            FechaIngreso = jDateChooser1.getDate();
            fecha = formateador.format(FechaIngreso);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Hubo un error con la fecha no se han podido guardar los cambios, intente nuevamente.", "Aviso", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        Double total = (double) this.tablaTotal.getValueAt(0, 0);
        DefaultTableModel modelo = (DefaultTableModel) this.tablaProductoIngresado.getModel();
        Integer cantFilas = modelo.getRowCount();
        ArrayList<ProductoIngresado> productos = new ArrayList();
        for (int j = 0; j < cantFilas; j++) {
            String nombre = (String) modelo.getValueAt(j, colNombre);
            Integer codProd;
            try {
                codProd = this.stock.getCodProducto(nombre);
            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(null, "Hubo un error al guardar los datos.", "Aviso", JOptionPane.ERROR_MESSAGE);
                return;
            }
            Double precio = (double) modelo.getValueAt(j, colPrecioU);
            Integer cant = (int) modelo.getValueAt(j, colCant);
            ProductoIngresado producto = new ProductoIngresado(codProd, precio, cant);
            productos.add(producto);

        }
        try {
            this.stock.ingreso(fecha, productos, total);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Hubo un error al guardar los datos.", "Aviso", JOptionPane.ERROR_MESSAGE);
            return;
        }
        this.dispose();
    }//GEN-LAST:event_btnConservarActionPerformed

    private void btnRechazarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRechazarActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnRechazarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(IngresoStock.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(IngresoStock.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(IngresoStock.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(IngresoStock.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                IngresoStock dialog = null;
                dialog = new IngresoStock(new javax.swing.JFrame(), true);

                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAgregar;
    private javax.swing.JButton btnConservar;
    private javax.swing.JButton btnQuitar;
    private javax.swing.JButton btnRechazar;
    private javax.swing.JComboBox jComboBox1;
    private com.toedter.calendar.JDateChooser jDateChooser1;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextField jTPrecio;
    private javax.swing.JLabel labelCantidad;
    private javax.swing.JSpinner spinnerCantidad;
    private javax.swing.JTable tablaProductoIngresado;
    private javax.swing.JTable tablaTotal;
    // End of variables declaration//GEN-END:variables
}
